package service;

import model.User;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户服务类 - 管理用户注册、登录、验证等
 */
public class UserService {
    private static final String USER_DATA_FILE = "users.dat";
    private Map<String, User> users;
    private Map<String, String> userSessions; // sessionId -> username

    public UserService() {
        this.users = new HashMap<>();
        this.userSessions = new HashMap<>();
        loadUsers();
        initializeDefaultAdmin();
    }

    /**
     * 用户注册
     */
    public boolean register(String username, String password, String role) {
        if (users.containsKey(username)) {
            return false; // 用户名已存在
        }

        if (!"admin".equals(role) && !"user".equals(role)) {
            role = "user"; // 默认角色为用户
        }

        User newUser = new User(username, password, role);
        users.put(username, newUser);
        saveUsers();
        return true;
    }

    /**
     * 用户登录
     */
    public String login(String username, String password) {
        User user = users.get(username);
        if (user != null && user.getPassword().equals(password)) {
            user.setLoggedIn(true);
            String sessionId = generateSessionId();
            userSessions.put(sessionId, username);
            saveUsers();
            return sessionId;
        }
        return null;
    }

    /**
     * 用户注销
     */
    public boolean logout(String sessionId) {
        String username = userSessions.get(sessionId);
        if (username != null) {
            User user = users.get(username);
            if (user != null) {
                user.setLoggedIn(false);
            }
            userSessions.remove(sessionId);
            saveUsers();
            return true;
        }
        return false;
    }


    /**
     * 根据sessionId获取用户
     */
    public User getUserBySession(String sessionId) {
        String username = userSessions.get(sessionId);
        return username != null ? users.get(username) : null;
    }

    /**
     * 验证用户权限
     */
    public boolean hasAdminPermission(String sessionId) {
        User user = getUserBySession(sessionId);
        boolean isAdmin = user != null && user.isAdmin();
        System.out.println("权限检查 - sessionId: " + sessionId + ", 用户: " +
                (user != null ? user.getUsername() : "null") + ", 是管理员: " + isAdmin);
        return isAdmin;
    }

    /**
     * 获取所有用户（仅管理员）
     */
    public Map<String, User> getAllUsers(String sessionId) {
        if (!hasAdminPermission(sessionId)) {
            return new HashMap<>();
        }
        return new HashMap<>(users);
    }

    /**
     * 获取用户数量
     */
    public int getUserCount() {
        return users.size();
    }
    /**
     * 删除用户（仅管理员）
     */
    public boolean deleteUser(String sessionId, String username) {
        if (!hasAdminPermission(sessionId)) {
            return false;
        }

        User currentUser = getUserBySession(sessionId);
        if (currentUser != null && currentUser.getUsername().equals(username)) {
            return false; // 不能删除自己
        }

        if (users.remove(username) != null) {
            // 清理该用户的session
            userSessions.entrySet().removeIf(entry -> entry.getValue().equals(username));
            saveUsers();
            return true;
        }
        return false;
    }

    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return UUID.randomUUID().toString();
    }

    /**
     * 加载用户数据
     */
    @SuppressWarnings("unchecked")
    private void loadUsers() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(USER_DATA_FILE))) {
            users = (Map<String, User>) ois.readObject();
        } catch (FileNotFoundException e) {
            System.out.println("用户数据文件不存在，将创建新文件");
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载用户数据失败: " + e.getMessage());
        }
    }

    /**
     * 保存用户数据
     */
    private void saveUsers() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(USER_DATA_FILE))) {
            oos.writeObject(users);
        } catch (IOException e) {
            System.err.println("保存用户数据失败: " + e.getMessage());
        }
    }

    /**
     * 初始化默认管理员账户
     */
    private void initializeDefaultAdmin() {
        if (!users.containsKey("admin")) {
            register("admin", "admin123", "admin");
            System.out.println("已创建默认管理员账户: admin/admin123");
        }else {
            System.out.println("默认管理员账户已存在");
        }
    }
}